package com.wu.controller;

import com.alibaba.dubbo.config.annotation.Reference;

import com.wu.pojo.bean.ExcelBean;
import com.wu.pojo.po.paperPo.Answer;
import com.wu.pojo.res.Result;
import com.wu.service.*;

import com.wu.utils.CommonUtils;
import com.wu.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.wu.constants.Constants.*;

/**
 * [资源管理]
 *
 * @Author : [wuzhengru]
 * @Version : [v1.0]
 * @Date : [2021/5/25 17:31]
 */
@RestController
@RequestMapping("/api/v1/excel")
@Slf4j
@Api(tags = "资源管理接口", description = "ResourceController")
public class ResourceController {

    @Autowired
    ResourceLoader resourceLoader;
    @Reference
    private PaperService paperService;
    @Reference
    private QuestionService questionService;
    @Reference
    private AnswerService answerService;
    @Reference
    private ExcelService excelService;
    @Reference
    private DataBakService dataBakService;

    /**
     * 上传EXCEL，存入temp表
     */
    @RequiresRoles("user")
    @ApiOperation("用户上传EXCEL备份数据")
    @PostMapping("upload")
    public Result ExcelImport(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {

        //1、参数验证

        //2、参数转换
        byte[] pic = file.getBytes(); //转换为字节流(dubbo不支持MultipartFile文件传输)
        String name = file.getOriginalFilename();

        //3、解析文件
        Result result = null;
        try {
            result = excelService.readExcelFile(pic, name);
        } catch (Exception e) {
            throw new RuntimeException("解析失败！",e);
        }
        return result;
    }

    /**
     * 上传EXCEL，验证转移
     * @param paperId 问卷id title 标题 token 用户信息
     */
    @RequiresRoles("user")
    @ApiOperation("EXCEL解析校验")
    @GetMapping("validExcel")
    public Result validExcel(@RequestParam String paperId, @RequestParam String title, @RequestParam String token){

        // 1、参数校验
        if (null == paperId || "".equals(paperId) || null == title || "".equals(title)) {
            // 通过userId删除备份表（===需新增userId参数===）
            Result.fail("有效信息缺失");
        }
        // 2、整理数据
        StringBuilder pk = new StringBuilder();
        pk.append(title).append("#").append((paperId.substring(0,5)));
        // 3、拿到temp表数据
        List<ExcelBean> excelBeans = excelService.queryBakAnswerListByPK(pk.toString());
        String bakPaperId = null;
        for (ExcelBean excelBean : excelBeans) {
            // 用paperId和questionNo查询questionId
            String questionId = questionService.queryQuestionByPaperIdAndQuestionNo(paperId, excelBean.getQuestionNo());
            Claims claimByToken = JwtUtils.getClaimByToken(token);
            String userId = null;
            try {
                userId = (String)claimByToken.get("userId");
            } catch (Exception e) {
                log.debug("token信息失效，请重新登录");
                return Result.fail("token信息失效，请重新登录");
            }
            Integer questionType = excelBean.getQuestionType();
            String answerContents = excelBean.getAnswer();

            // 一条一条进行逻辑校验
            // 拼装选项格式
            // 拼装选项，统一格式

            // 转移入库
            Answer answer = new Answer();
            answer.setAnswerId(CommonUtils.getUUID()).setPaperId(paperId).setQuestionId(questionId).setUserId(userId)
                    .setQuestionType(questionType).setAnswerContents("["+answerContents.trim()+"]");
            answerService.insertAnswer(answer);

            // 返回temp表paperId供用户查询解析后答案(此paperId是拼接后的id)
            bakPaperId = excelBean.getPaperId();
        }
        //3、解析文件

        return Result.succ("解析成功!",bakPaperId);
    }

    /**
     * 上传EXCEL，请求填写答案列表
     * @param paperId 问卷拼接id
     *        后期优化校验逻辑需要此方法
     */
    @ApiIgnore
    @GetMapping("commitTempAnswer")
    public Result commitTempAnswer(@RequestParam String paperId){

        //1、整理数据
        List<ExcelBean> excelBeans = excelService.queryBakAnswerListByPK(paperId);
        List<String> answers = new ArrayList<>();
        // 把temp表中的答案列表遍历出来返回
//        answers.addAll(excelBeans.get(0).getAnswerContents());
        // 删除temp表数据

        return Result.succ("验证转移成功!");
    }


    /**
     * 获取EXCEL路径
     */
    @RequiresRoles("user")
    @ApiOperation("获取EXCEL模板路径")
    @GetMapping("getExcelPath")
    public Result getExcelPath(@RequestParam String  paperId){

        //1、参数验证
        if (paperId == null || "".equals(paperId)) {
            Result.fail("问卷ID未传入");
        }

        //2、查询ExcelPath
        String excelPath = paperService.getExcelPath(paperId);

        return Result.succ(excelPath);
    }

    /**
     * 上传图片，生成路径
     */
    @ApiOperation("用户上传图片，生成路径")
    @PostMapping(value = "/uploadPic")
    @ResponseBody
    public Result uploadPic(@RequestParam("file") MultipartFile picture) {

        String name = picture.getOriginalFilename();// 获取文件名
        String pictureName = CommonUtils.getUUID().concat(".").concat(name.substring(name.lastIndexOf(".") + 1));// 生成文件名
        String filePath = PREFIX_PICTURE.concat(pictureName);// 生成相对路径
        log.info("文件路径:" + filePath);
        try {
            picture.transferTo(new File(ROOT_PATH.concat(filePath)));// 完整路径
        } catch (Exception e) {
            throw new RuntimeException("保存图片失败",e);
        }
        return Result.succ(filePath);
    }

    /**
     * excel解析暂未做约束，下个版本需重点更改
     * (？？？未做约束，下个版本再做？？？)
     *  sheet： title+paperId
     *  上传-》流生成excel=》入库成功，
     *  code === 200 ->
     *  传入paperId，userId， 校验 papeId==bak.paperId，
     *  对比问卷标题、行数、列数，单选题=>无符号，多选题=>逗号分割后判断有无符号
     *  解析完成，设置标志位，传入问卷详情，点击提交，全表 select * 更新过来，修改paperId，删除temp表
     *          失败则回滚
     *  检查行更新一行
     *  更新新表 通过title 和 like paperId 查到paperId，拿到userId，更新表update answer set () value（）
     */
}

